<template>
  <div class="app-container">
    <div class="filter-container">
      <FilterItems
        :filter-items="filterItems"
        :domain="listQuery.domain"
        :configs="configs"
        class="filter-item"
      />

      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>

      <el-button
        v-if="checkHidden(handle, 'create')"
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        {{
          handle && handle.create && handle.create.text
            ? handle.create.text
            : '添加'
        }}
      </el-button>

      <el-button
        v-if="checkHidden(handle, 'export')"
        type="success"
        title="导出前请刷新页面"
        class="filter-item"
        style="margin-left:5px;"
        @click="exportCheck"
      >
        导出EXCEL
      </el-button>
    </div>

    <TableList
      ref="tableList"
      :model-name="modelName"
      :detail-page="detailPage"
      :details-func="detailsFunc"
      :list="list"
      :list-loading="listLoading"
      @handle-click="handleClick"
    />

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 表单 :model-name="modelName" @changed="getData" -->
    <FormDialog
      ref="formDialog"
      :model-name="modelName"
      @changed="getData"
      @created="getNewData"
    />
  </div>
</template>

<script>
import odoo from '@/odooapi'

import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import FilterItems from './FilterItems'

import TableList from '@/selfComponents/TableList'
import FormDialog from '@/selfComponents/FormDialog'

import { parseTime } from '@/utils'

export default {
  name: 'ListPage',
  components: { Pagination, FilterItems, TableList, FormDialog },
  directives: { waves },
  filters: {},

  props: {
    modelName: { type: String, default: '' },
    detailPage: { type: String, default: undefined },
    detailsFunc: { type: Function, default: undefined }
  },

  data() {
    return {
      Model: undefined,
      listLoading: false,

      total: 0,
      list: [],
      filterItems: [],

      listQuery: {
        page: 1,
        limit: 10,
        domain: {}
        //   order: 'id'
      },
      configs: {}
    }
  },

  watch: {},

  async created() {
    this.Model = odoo.env(this.modelName)

    // eslint-disable-next-line object-curly-spacing
    const { filterItems, handle = {} } = this.Model.configs

    const handle_create = handle.create || {}
    const handle_export = handle.export || {}

    this.handle = {
      create: {
        hidden: handle_create.hidden || false,
        text: handle_create.text || '添加'
      },
      export: {
        hidden: handle_export.hidden || false,
        text: handle_export.text || '添加'
      }
    }

    if (handle.create) {
      const hidden_fn = handle.create.hidden

      if (hidden_fn && typeof hidden_fn === 'function') {
        this.handle.create.hidden = hidden_fn({ self: this.Model })
      }
    }

    if (handle.export) {
      const hidden_fn = handle.export.hidden

      if (hidden_fn && typeof hidden_fn === 'function') {
        this.handle.export.hidden = hidden_fn({ self: this.Model })
      }
    }

    this.filterItems = await this.Model.filterOptions(filterItems)

    this.configs = {
      get_options: fi => {
        // 在configs中定义了该函数, 返回 options
        // 该 options 与当前 domain 中的数据有关
        return fi.options_for_select({
          self: this.Model,
          options_for_select: fi.options_for_select_init,
          items: this.filterItems,
          domain: this.listQuery.domain
        })
      }
    }

    const domainItems = filterItems.reduce((acc, cur) => {
      acc[cur.name] = cur.default || undefined
      return acc
    }, {})

    this.listQuery.domain = domainItems || {}
    this.flashData()
  },
  // mounted() {},

  methods: {
    exportCheck() {
      const fileName = this.modelName
      this.$refs['tableList'].exportCheck({ fileName })
    },

    checkHidden(handle, type) {
      if (handle[type] && handle[type].hidden) {
        return !handle[type].hidden
      } else {
        return true
      }
    },

    async getList() {
      // 翻页功能, page, limit 变了 刷新数据
      // 搜索按钮触发, domain page 变了 刷新数据

      // 通知子组件 tablelist 需要刷数据
      // this.$refs['tableList'].handleFlashData(this.listQuery)
      this.flashData()
    },

    async flashData() {
      this.listLoading = true

      // 判断 过滤条件 为空, 则 不再向下传递
      // TBD 如果需要查询 null 时, 必须特殊处理
      const domain = Object.keys(this.listQuery.domain).reduce((acc, item) => {
        if (this.listQuery.domain[item]) {
          acc[item] = this.listQuery.domain[item]
        }
        return acc
      }, {})

      this.list = await this.Model.search({ ...this.listQuery, domain })

      // if (this.list.length) {
      //   odoo.check_config({
      //     record: this.list[0],
      //     columns: this.columns,
      //     label: '列表字段'
      //   })
      // }

      this.total = await this.Model.search_count(domain)
      this.listLoading = false
    },

    handleClick(row, { handle }) {
      if (handle === 'update') {
        this.handleUpdate(row)
      } else if (handle === 'remove') {
        this.handleRemove(row)
      }
    },
    handleCreate() {
      this.$refs['formDialog'].handleCreate()
    },
    handleUpdate(row) {
      this.$refs['formDialog'].handleUpdate(row)
    },
    handleRemove(row) {
      // console.log(row)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await this.Model.unlink(row)
          if (res) {
            this.flashData()

            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    async getNewData(rid) {
      //      this.flashData()
      // 新增后 根据新增 id, 查询数据 并插入到第一行
      // 针对 find or create 的需求, 需要在原有list中查询该新id已有的行，并过滤调
      const res = await this.Model.browse(rid)
      const list = this.list.filter(item => item.id !== rid)
      this.list = [...res, ...list]
      this.$refs['tableList'].setCurrentRow(this.list[0])
    },

    async getData() {
      this.flashData()
    },

    handleFilter() {
      // 搜索按钮触发, domain 变了
      // 重置页面为首页 刷新数据

      this.filterItems.forEach(item => {
        if (item.type === 'date_month') {
          const date_month = this.listQuery.domain[item.name]

          if (date_month) {
            const new_date = `${parseTime(date_month, '{y}-{m}')}-01`
            this.listQuery.domain[item.name] = new_date
          }
        } else if (item.type === 'date') {
          const date = this.listQuery.domain[item.name]

          if (date) {
            const new_date = parseTime(date, '{y}-{m}-{d}')
            this.listQuery.domain[item.name] = new_date
          }
        } else if (item.type === 'date_year') {
          const date_year = this.listQuery.domain[item.name]

          if (date_year) {
            // 便于 重写 search 函数
            if (!item.no_format) {
              const new_date = `${parseTime(date_year, '{y}')}-01-01`
              this.listQuery.domain[item.name] = new_date
            }
          }
        }
      })

      this.listQuery.page = 1
      // this.getList()
      this.flashData()
    }
  }
}
</script>
